﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class ManagerController : ManageController
    {
        protected BaseApi _service = new BaseApi();
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            ViewBag.action = _action;
            ViewBag.id = _id;
        }

        #region 管理日志
        [ChkAdminScript("manager_log", DTEnums.ActionEnum.View)]
        public ActionResult Manager_Log()
        {
            return View();
        }

        #region 组合SQL查询语句
        protected string ManagerLogCombSqlTxt(string _start_time, string _end_time, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_start_time))
            {
                _start_time = Utils.StrToDateTime(_start_time).ToString();
                strTemp.Append(" and datediff(s,add_time,'" + _start_time + "')<=0");
            }
            if (!string.IsNullOrEmpty(_end_time))
            {
                _end_time = Utils.StrToDateTime(_end_time).ToString();
                strTemp.Append(" and datediff(s,add_time,'" + _end_time + "')>=0");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (user_name like  '%" + _keywords + "%' or action_type like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("manager_log", DTEnums.ActionEnum.View)]
        public JsonResult ManagerLogList(string start, string end, string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + ManagerLogCombSqlTxt(start, end, keywords);
            string strOrder = "add_time desc,id desc";
            var resultList = _service.ManagerLogBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 日志删除 7天前
        [ChkAdminJson("manager_log", DTEnums.ActionEnum.Delete)]
        public JsonResult ManagerLogDelete()
        {
            return _service.ManagerLogDelete();
        }
        #endregion
        #endregion

        #region 角色管理
        [ChkAdminScript("manager_role", DTEnums.ActionEnum.View)]
        public ActionResult Role_List()
        {
            return View();
        }

        #region 组合SQL查询语句==========================
        protected string ManagerRoleCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and role_name like '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定    
        [ChkAdminJson("manager_role", DTEnums.ActionEnum.View)]
        public JsonResult ManagerRoleList(string keywords)
        {
            string strWhere = "role_type>=" + managerModel.role_type + ManagerRoleCombSqlTxt(keywords);
            string strOrder = string.Empty;
            List<Model.manager_role> resultList = _service.ManagerRoleBind(strWhere, strOrder);
            return Json(new { status = 1, msg = "", item = resultList });
        }
        #endregion

        #region 删除
        [HttpPost]
        [ChkAdminJson("manager_role", DTEnums.ActionEnum.Delete)]
        public JsonResult ManagerRoleDelete(List<int> ids)
        {
            return _service.ManagerRoleDelete(ids);
        }
        #endregion

        #region 编辑、添加
        [ChkAdminScript("manager_role", DTEnums.ActionEnum.View)]
        public ActionResult Role_Edit()
        {
            Model.manager_role model = new Model.manager_role();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                _action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.ManagerRoleInfo(_id);
                if (model == null)
                {
                    return ResultMsg("角色不存在或已被删除！", "back");
                }
            }
            ViewBag.roleList = _service.RoleTypeBind(); //绑定角色类型
            ViewBag.navList = _service.SysNavigationBind(); //绑定导航
            return View(model);
        }

        [HttpPost]
        public ActionResult ManagerRoleSave(string json, string role_name, int role_type)
        {
            SaveModel save = _service.ManagerRoleSave(_action, _id, json, role_name, role_type);
            save.url = save.status == 0 ? "back" : "../manager/role_list";
            return Json(save);
        }
        #endregion
        #endregion

        #region 修改密码
        public ActionResult Manager_Pwd()
        {
            return View(managerModel);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult ManagerPwdSave(Model.manager t)
        {
            BLL.manager bll = new BLL.manager();
            string txtOldPassword = DTRequest.GetFormString("txtOldPassword");
            string txtPassword = DTRequest.GetFormString("txtPassword1");
            if (DESEncrypt.Encrypt(txtOldPassword.Trim(), managerModel.salt + DTKeys.SECURITY_CODE) != managerModel.password)
            {
                return ResultMsg("旧密码不正确！", "");
            }
            if (t.password.Trim() != txtPassword.Trim())
            {
                return ResultMsg("两次密码不一致！", "");
            }
            managerModel.password = DESEncrypt.Encrypt(t.password.Trim(), managerModel.salt + DTKeys.SECURITY_CODE);
            managerModel.real_name = t.real_name;
            managerModel.telephone = t.telephone;
            managerModel.email = t.email;

            if (!bll.Update(managerModel))
            {
                return Json(new { status = 0, msg = "保存过程中发生错误！" });
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改密码"); //记录日志
            return Json(new { status = 1, msg = "密码修改成功！", url = "../home/login" });
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult ManagerSave(Model.manager t)
        {
            SaveModel save = _service.ManagerSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../manager/manager_list";
            return Json(save);
        }
        #endregion

        #region 管理员管理
        [ChkAdminScript("manager_list", DTEnums.ActionEnum.View)]
        public ActionResult Manager_List()
        {
            return View();
        }
        #region 组合SQL查询语句==========================
        protected string ManagerCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (user_name like  '%" + _keywords + "%' or real_name like '%" + _keywords + "%' or email like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("manager_list", DTEnums.ActionEnum.View)]
        public JsonResult ManagerList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "role_type>=" + managerModel.role_type + ManagerCombSqlTxt(keywords);
            string strOrder = "id desc";
            var resultList = _service.ManagerBind(strWhere, strOrder, page, limit);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("roleTitle", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["add_time"] = item["add_time"];
                    row["email"] = item["email"];
                    row["telephone"] = item["telephone"];
                    row["real_name"] = item["real_name"];
                    row["user_name"] = item["user_name"];
                    row["id"] = item["id"];
                    row["is_lock"] = item["is_lock"];
                    row["roleTitle"] = new BLL.manager_role().GetTitle(Utils.ObjToInt(item["role_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 删除
        [HttpPost]
        [ChkAdminJson("manager_list", DTEnums.ActionEnum.Delete)]
        public JsonResult ManagerDelete(List<int> ids)
        {
            return _service.ManagerDelete(ids);
        }
        #endregion

        #region 修改管理员状态
        [HttpPost]
        [ChkAdminJson("manager_list", DTEnums.ActionEnum.Edit)]
        public JsonResult ManagerLock(int id, bool is_lock)
        {
            BLL.manager bll = new BLL.manager();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }
        #endregion

        #region 编辑、添加
        [ChkAdminScript("manager_list", DTEnums.ActionEnum.View)]
        public ActionResult Manager_Edit()
        {
            Model.manager model = new Model.manager();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                _action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.ManagerInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                model.password = "0|0|0|0";
                ViewBag.ClientScript = Jscript("$('#user_name').removeAttr('ajaxurl').attr('readonly','true');");
            }
            ViewBag.roleList = _service.ManagerRoleBind(managerModel.role_type); //绑定角色类型
            ViewBag.DefaultPassword = model.password;
            return View(model);
        }
        #endregion

        #endregion
    }
}
